package com.qianji.petmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianji.common.to.GiteeUserVo;
import com.qianji.common.utils.HttpUtils;
import com.qianji.common.utils.PageUtils;
import com.qianji.common.utils.Query;
import com.qianji.petmall.member.dao.MemberDao;
import com.qianji.petmall.member.entity.MemberEntity;
import com.qianji.petmall.member.entity.MemberLevelEntity;
import com.qianji.petmall.member.exception.PhoneException;
import com.qianji.petmall.member.exception.UserNameException;
import com.qianji.petmall.member.service.MemberService;
import com.qianji.petmall.member.vo.MemberLoginVo;
import com.qianji.petmall.member.vo.MemberRegisVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelServiceImpl memberLevelService;

    @Override
    public void addRegis(MemberRegisVo memberRegisVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级【普通会员】
        MemberLevelEntity defaultStatus = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq(
                "default_status", 1));
        memberEntity.setLevelId(defaultStatus.getId());
        // 检查手机号 用户名是否唯一
        String phone = memberRegisVo.getPhone();
        String userName = memberRegisVo.getUserName();
        checkPhone(phone);
        checkUserName(userName);

        memberEntity.setUsername(memberRegisVo.getUserName());
        memberEntity.setMobile(phone);
        //密码采用MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String passWord = bCryptPasswordEncoder.encode(memberRegisVo.getPassWord());

        memberEntity.setPassword(passWord);
        this.save(memberEntity);
    }
    @Override
    public void checkPhone(String phone) throws PhoneException{
        // 检查手机号否唯一
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count>0){
            //说明手机号重复
            throw new PhoneException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String loginzh = memberLoginVo.getLoginzh();
        String passWord = memberLoginVo.getPassWord();
        //数据库查询账号密码
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginzh).or().eq("mobile", loginzh));
        if (memberEntity == null){
            //登录失败
            return null;
        }else {
            String passwordMysql = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = bCryptPasswordEncoder.matches(passWord, passwordMysql);
            if (matches){
                //登录成功
                return memberEntity;
            }else {
                //登录失败
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(GiteeUserVo giteeUserVo) throws Exception {
        //登录和注册合并逻辑
        Map<String, String> map = new HashMap<>();
        map.put("access_token", giteeUserVo.getAccessToken());
        //查询当前用户的社交信息
        HttpResponse get = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);
        String json = EntityUtils.toString(get.getEntity());
        JSONObject object = JSON.parseObject(json);
        String uid = object.getString("id");
        String name = object.getString("name");
        String avatar_url = object.getString("avatar_url");
        //1、判断当前社交用户是否已经登录过系统
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity!=null){
            //这个用户已经注册了，更新令牌
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(giteeUserVo.getAccessToken());
            memberEntity.setExpiresIn(giteeUserVo.getExpiresIn());
            this.baseMapper.updateById(memberEntity);
            entity.setAccessToken(giteeUserVo.getAccessToken());
            entity.setExpiresIn(giteeUserVo.getExpiresIn());
            return entity;
        }else{
            //这个用户没有注册
            MemberEntity member = new MemberEntity();
            try {
                if (get.getStatusLine().getStatusCode()==200){
                    //防止出现网络情况
                    member.setUsername(name);
                    member.setNickname(name);
                    member.setHeader(avatar_url);
                    //....
                }
            }catch (Exception e){}
            member.setSocialUid(uid);
            member.setCreateTime(new Date());
            member.setExpiresIn(giteeUserVo.getExpiresIn());
            member.setAccessToken(giteeUserVo.getAccessToken());

            this.baseMapper.insert(member);
            return member;
        }
    }

    @Override
    public void checkUserName(String userName) throws UserNameException{
        // 检查用户名是否唯一
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count>0){
            //说明用户名重复
            throw new UserNameException();
        }
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

}